package za.ac.wits.was.user.service;

import java.util.Set;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import za.ac.wits.was.courses.allocations.CourseAllocations;
import za.ac.wits.was.research.ResearchAllocations;
import za.ac.wits.was.user.model.AcademicStaff;

/**
 *
 * @author Salman Noor : School of Electrical and Information Engineering
 * @Copyright: Wits University 2013 - All Rights Reserved
 * @email: salmannoor74415@gmail.com
 * @License: BSD License (http://www.linfo.org/bsdlicense.html)
 */
@Service
public class UserTimeService {

    private SessionFactory sessionFactory;
    private Integer TotalTeachingHours;
    private Integer ActualTeachingHours;
    private Integer RemainingTeachingHours;
    private Integer TotalResearchHours;

    @JsonIgnore
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @JsonIgnore
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void calculateAllStats(String username) {
        Session sess = this.sessionFactory.openSession();
        AcademicStaff academicStaffUser = (AcademicStaff) sess.createQuery("from was_user where username = :username").setParameter("username", username).uniqueResult();
        this.TotalTeachingHours = academicStaffUser.getTotal_hours() * academicStaffUser.getTeaching_percentage() / 100;
        Set<CourseAllocations> ca = academicStaffUser.getCourse_allocations();
        this.ActualTeachingHours = 0;
        if (ca != null) {
            for (CourseAllocations c : ca) {
                if (c.getPending() == false && c.getApproved() == true) {
                    this.ActualTeachingHours += c.getCourse().getCourse_hours();
                }
            }
        }

        this.RemainingTeachingHours = this.TotalTeachingHours - this.ActualTeachingHours;
        Set<ResearchAllocations> ra = academicStaffUser.getResearch_allocations();
        this.TotalResearchHours = 0;
        if (ra != null) {
            for (ResearchAllocations r : ra) {
                if (r.getApproved() == true && r.getPending() == false) {
                    this.TotalResearchHours += r.getResearch_hours();
                }
            }
        }

        sess.flush();
        sess.close();
    }

    public Integer getTotalTeachingHours() {
        return TotalTeachingHours;
    }

    public Integer getActualTeachingHours() {
        return ActualTeachingHours;
    }

    public Integer getRemainingTeachingHours() {
        return RemainingTeachingHours;
    }

    public Integer getTotalResearchHours() {
        return TotalResearchHours;
    }

}
